package com.znufe.exam.controller.admin;

import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.base.RestResponse;
import com.znufe.exam.configuration.config.annotation.Log;
import com.znufe.exam.configuration.config.entity.AjaxResult;
import com.znufe.exam.configuration.config.enums.BusinessType;
import com.znufe.exam.configuration.config.model.LoginUser;
import com.znufe.exam.configuration.config.service.TokenService;
import com.znufe.exam.configuration.config.utils.SecurityUtils;
import com.znufe.exam.configuration.config.utils.ServletUtils;
import com.znufe.exam.domain.SysRole;
import com.znufe.exam.domain.other.KeyValue;
import com.znufe.exam.domain.User;
import com.znufe.exam.domain.UserEventLog;
import com.znufe.exam.domain.enums.UserStatusEnum;
import com.znufe.exam.service.AuthenticationService;
import com.znufe.exam.service.ISysRoleService;
import com.znufe.exam.service.UserEventLogService;
import com.znufe.exam.service.UserService;
import com.znufe.exam.utility.DateTimeUtil;
import com.znufe.exam.viewmodel.admin.user.*;
import com.znufe.exam.utility.PageInfoHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author alvis
 */
@RestController("AdminUserController")
@RequestMapping(value = "/api/admin/user")
@AllArgsConstructor
public class UserController extends BaseApiController {

    private final UserService userService;
    private final UserEventLogService userEventLogService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysRoleService roleService;

    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    @ApiOperation(value = "分页展示用户信息",notes = "参数：无参数/按用户名/按角色+分页信息")
    @ApiImplicitParam(paramType="body", name = "requestVM", value = "用户名+角色+分页信息", dataType = "UserPageRequestVM",required = true)
    public RestResponse<PageInfo<UserResponseVM>> pageList(@RequestBody UserPageRequestVM requestVM) {
        requestVM.setUserName(requestVM.getUserName().trim());
        PageInfo<User> pageInfo = userService.userPage(requestVM);
        PageInfo<UserResponseVM> page = PageInfoHelper.copyMap(pageInfo, d -> UserResponseVM.from(d));
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/event/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserEventLogVM>> eventPageList(@RequestBody UserEventPageRequestVM model) {
        model.setUserName(model.getUserName().trim());
        PageInfo<UserEventLog> pageInfo = userEventLogService.page(model);
        PageInfo<UserEventLogVM> page = PageInfoHelper.copyMap(pageInfo, d -> {
            UserEventLogVM vm = modelMapper.map(d, UserEventLogVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(d.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }

    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/","/select/{id}"})
    @ApiOperation(value = "根据id查找用户",notes = "返回部分用户信息")
    @ApiImplicitParam(paramType="path", name = "id", value = "用户id", dataType = "int",required = false)
    public AjaxResult select(@PathVariable(value = "id",required = false) Integer id) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("roles",roleService.selectRoleAll());
        if (com.znufe.exam.configuration.config.utils.StringUtils.isNotNull(id)){
            User user = userService.getUserById(id);
            UserResponseVM userVm = UserResponseVM.from(user);
            ajax.put(AjaxResult.DATA_TAG,userVm);
            ajax.put("roleIds",roleService.selectRoleListByUserId(id.longValue()));
        }
        return ajax;
    }

    @RequestMapping(value = "/current", method = RequestMethod.POST)
    @ApiOperation(value = "查找当前用户",notes = "返回部分用户信息，无参数")
    public RestResponse<UserResponseVM> current() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        User user = loginUser.getUser();
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }

    @PreAuthorize("@ss.hasAnyPermi('system:user:add,system:user:update')")
    @Log(title = "用户管理", businessType = BusinessType.EDIT)
    @PostMapping(value = "/edit")
    @ApiOperation(value = "管理端：新建用户与修改用户信息",notes = "修改用户信息需要传用户id")
    @ApiImplicitParam(paramType="body", name = "model", value = "创建用户所需信息", dataType = "UserCreateVM",required = true)
    public RestResponse<User> edit(@RequestBody @Valid UserCreateVM model) {
        //create
        if (model.getId() == null) {
            User existUser = userService.getUserByUserName(model.getUserName());

            if (null != existUser) {
                return new RestResponse<>(2, "用户已存在");
            }

            if (StringUtils.isBlank(model.getPassword())) {
                return new RestResponse<>(3, "密码不能为空");
            }

            if (model.getRoleIds().length == 0){
                return new RestResponse<>(4,"未分配角色");
            }
        }
        if (StringUtils.isBlank(model.getBirthDay())) {
            model.setBirthDay(null);
        }
        User user = modelMapper.map(model, User.class);

        if (model.getId() == null) {
            //String encodePwd = authenticationService.pwdEncode(model.getPassword());
            user.setPassword(SecurityUtils.encryptPassword(model.getPassword()));
            user.setUserUuid(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setStatus(0);
            user.setLastActiveTime(new Date());
            user.setDeleted(0);
            userService.insertByFilter(user);
        } else {
            user.setModifyTime(new Date());
            userService.updateByIdFilter(user);
        }
        return RestResponse.ok(user);
    }

    @PreAuthorize("@ss.hasPermi('system:user:update')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value = "管理端：更新用户信息",notes = "修改真实姓名和电话号码")
    @ApiImplicitParam(paramType="body", name = "model", value = "更新用户所需信息", dataType = "UserUpdateVM",required = true)
    public RestResponse update(@RequestBody @Valid UserUpdateVM model) {
        User user = userService.selectById(getCurrentUser().getId());
        modelMapper.map(model, user);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }

    @PreAuthorize("@ss.hasPermi('system:user:update')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/changeStatus/{id}")
    @ApiOperation(value = "修改用户状态")
    @ApiImplicitParam(paramType="path", name = "id", value = "用户ID",dataType = "int",required = true)
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserStatusEnum userStatusEnum = UserStatusEnum.fromCode(user.getStatus());
        Integer newStatus = userStatusEnum == UserStatusEnum.Enable ?
                UserStatusEnum.Disable.getCode() :
                UserStatusEnum.Enable.getCode();
        user.setStatus(newStatus);
        user.setModifyTime(new Date());
        userService.updateById(user);
        return RestResponse.ok(newStatus);
    }

    @PreAuthorize("@ss.hasPermi('system:user:delete')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @GetMapping(value = "/delete/{id}")
    @ApiOperation(value = "管理端：删除用户")
    @ApiImplicitParam(paramType="path", name = "id", value = "用户ID",dataType = "int",required = true)
    public RestResponse delete(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        user.setDeleted(1);
        userService.updateById(user);
        return RestResponse.ok();
    }


    @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    @ApiOperation(value = "管理端：根据用户名查找用户")
    @ApiImplicitParam(paramType="body", name = "userName", value = "用户名",dataType = "String",required = true)
    public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName) {
        List<KeyValue> keyValues = userService.selectByUserName(userName);
        return RestResponse.ok(keyValues);
    }

    @PreAuthorize("@ss.hasPermi('system:user:resetpwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/resetPassword/{id}")
    @ApiOperation(value = "管理端：重置管理员密码")
    public RestResponse resetPassword(@PathVariable("id") Integer id){
        User exitUser = userService.getUserById(id);
        String encodePwd = SecurityUtils.encryptPassword("123456");
        exitUser.setPassword(encodePwd);
        exitUser.setModifyTime(new Date());
        userService.updateById(exitUser);
        return RestResponse.ok();
    }

}
